<?php

class site_privilege_model extends CI_Model {

    protected $_instance = array(
        'table' => 'site_privilege',
        'primaryKey' => 'id',
    );
    public $_data = null;

    public function get_privileges() {
        $query = $this->db->get($this->_instance['table']);
        $list_privilege = array();
        foreach ($query->result() as $row) {
            $list_privilege[] = $row;
        }
        $query->free_result();
        return $list_privilege;
    }

    public function get_system_privileges() {
        global $privileges;
        return $privileges;
    }

    public function add_privilege($data) {
        $data = $this->auto_render($data);
        $CI = & get_instance();
        if (empty($data['name'])) {
            throw new Exception('Tên quyền hạn không được để trống');
            return false;
        }
        $data['user_id'] = $CI->session->userdata('admin_id');
        if (empty($data['error'])) {
            $this->db->insert($this->_instance['table'], $data);
        } else {
            throw new Exception($data['error']);
            return false;
        }
        return $this;
    }
    
    public function update_privilege($id, $data) {
        $data = $this->auto_render($data);
        $CI = & get_instance();
        if (empty($data['name'])) {
            throw new Exception('Tên quyền hạn không được để trống');
            return false;
        }
        $data['user_id'] = $CI->session->userdata('admin_id');
        if (empty($data['error'])) {
            $this->db->where('id', $id);
            $this->db->update($this->_instance['table'], $data);
        } else {
            throw new Exception($data['error']);
            return false;
        }
        return $this;
    }
    
    public function load_by_id($id) {
        $query = $this->db->get_where($this->_instance['table'], array('id' => $id), 1, 0);
        $this->_data = $query->row();
        $query->free_result();
        return $this->_data;
    }
    
    public function delete_privilege($id) {
        $this->db->delete($this->_instance['table'], array('id' => $id)); 
        return $this;
    }

    private function auto_render($data) {
        return $data;
    }

    public function get_system_privilege_list() {
        global $privileges;
        $list_privileges = array();
        foreach ($privileges as $group) {
            foreach ($group['children'] as $privilege) {
                $list_privileges[$privilege['alias']] = $privilege;
            }
        }
        return $list_privileges;
    }
}
?>